<?php
namespace app\common\model;

use app\admin\model\State;
use app\admin\model\Stores;
use app\common\traits\Gate;
use app\common\traits\SendMessage;
use app\common\traits\Text;
use app\common\traits\Wechat;
use Carbon\Carbon;
use think\Db;
use think\helper\Time;
use think\Model;

class Order extends Model
{
    use Gate;
    use Text;
    use Wechat;
    use SendMessage;

    protected $type = [
        'yctime'=>'timestamp:Y-m-d',//预产期
        'sjtime'=>'timestamp:Y-m-d',//收集日期
        'yypstime'=>'timestamp:Y-m-d G:i',//预约拍摄时间
        'qxpstime'=>'timestamp:Y-m-d',//取消拍摄时间
        'wdpstime'=>'timestamp:Y-m-d',//未到拍摄时间
        'zztime'=>'timestamp:Y-m-d',//追踪时间
        'jdtime'=>'timestamp:Y-m-d G:i',//建单时间
        'cztime'=>'timestamp:Y-m-d',//最后操作时间
        'yyfptime'=>'timestamp:Y-m-d',//邀约分配时间
        'hsfptime'=>'timestamp:Y-m-d',//会所分配时间
        'hsldtime'=>'timestamp:Y-m-d',//会所领单时间
        'yysktime'=>'timestamp:Y-m-d G:i',//邀约上课时间,报名
        'hskktime'=>'timestamp:Y-m-d',//会所旷课时间
        'skcgtime'=>'timestamp:Y-m-d',//会所上课成功时间
        'qxyytime'=>'timestamp:Y-m-d',//会所取消预约上课时间
        'fktime'=>'timestamp:Y-m-d',//反馈时间
        'yycgtime'=>'timestamp:Y-m-d',//预约成功时间
        'automsgtime'=>'timestamp:Y-m-d G:i',//分配专员指定系统自动给顾客发短信时间
        'cgpstime' =>'timestamp:Y-m-d'//成功拍摄时间
    ];

    //设置cztime最后操作时间自动更新
    protected $autoWriteTimestamp = true;
    protected $createTime = 'cztime';
    protected $updateTime = 'cztime';

    /**  条件筛选
     * @param $data   表单提交的数据
     * @return mixed  where条件
     */
    public  function map($data){
        //提醒操作
        if(!empty($data['txact'])){
            $map = $this->maptixing($data['txact']);
        }

        //ID
        if(!empty($data['id'])){
            trim($data['id']);
            $map['id']=['eq',$data['id']];
        }
        //顾客姓名
        if(!empty($data['name'])){
            trim($data['name']);
            $map['name']=['eq',$data['name']];
        }
        //妈妈手机
        if(!empty($data['maphone'])){
            trim($data['maphone']);
            $map['maphone']=['eq',$data['maphone']];
        }
        //家人手机
        if(!empty($data['otherphone'])){
            trim($data['otherphone']);
            $map['otherphone']=['eq',$data['otherphone']];
        }
        //微信
        if(!empty($data['weixin'])){
            trim($data['weixin']);
            $map['weixin']=['eq',$data['weixin']];
        }
        //QQ
        if(!empty($data['qq'])){
            trim($data['qq']);
            $map['qq']=['eq',$data['qq']];
        }
        //网络部渠道来源
        if(!empty($data['qudao'])){
            $map['qudao']=['eq',$data['qudao']];
        }
        //照片分类
        if(!empty($data['fenlei'])){
            $map['fenlei']=['eq',$data['fenlei']];
        }
        //省市
        if(!empty($data['city'])){
            $map['city']=['eq',$data['city']];
        }
        //区域
        if(!empty($data['area'])){
            $map['area']=['eq',$data['area']];
        }
        //收集医院
//        if(!empty($data['yiyuan'])){
//            $map['yiyuan']=['eq',$data['yiyuan']];
//        }
        if(!empty($data['yiyuan'])){
            $map['yiyuan']=['in',$data['yiyuan']];
        }
        //门诊
        if(!empty($data['menzhen'])){
            $map['menzhen']=['eq',$data['menzhen']];
        }
        //收集日期
        if(!empty($data['sjtime']) ){
            $sjtime = time_StrToArr($data['sjtime']);
            $map['sjtime']=['between time',$sjtime];
        }
        //预产期
        if(!empty($data['yctime'])){
            $yctime = time_StrToArr($data['yctime']);
            $map['yctime']=['between time',$yctime];
        }
        //建单客服
        if(!empty($data['jdry'])){
            $map['jdry']=['eq',$data['jdry']];
        }
        //建单时间
        if(!empty($data['jdtime']) ){
            $jdtime = time_StrToArr($data['jdtime']);
            $map['jdtime']=['between time',$jdtime];
        }
        //建单部门
        if(!empty($data['qd_depar']) ){
            $map['qd_depar']=['eq',$data['qd_depar']];
        }
        //邀约客服
        if(!empty($data['yykf'])){
            $map['yykf']=['eq',$data['yykf']];
        }
        //预约场馆
        if(!empty($data['yycg'])){
            $map['yycg']=['eq',$data['yycg']];
        }
        //业务状态
        if(!empty($data['ywstate'])){
            $map['ywstate']=['eq',$data['ywstate']];
        }
        //追踪日期
        if(!empty($data['zztime']) ){
            $zztime = time_StrToArr($data['zztime']);
            $map['zztime']=['between time',$zztime];
        }
        //预约成功时间
        if(!empty($data['yycgtime']) ){
            $yycgtime = time_StrToArr($data['yycgtime']);
            $map['yycgtime']=['between time',$yycgtime];
        }
        //预约拍摄时间
        if(!empty($data['yypstime']) ){
            $yypstime = time_StrToArr($data['yypstime']);
            $map['yypstime']=['between time',$yypstime];
        }
        //取消拍摄时间
        if(!empty($data['qxpstime'])){
            $qxpstime = time_StrToArr($data['qxpstime']);
            $map['qxpstime']=['between time',$qxpstime];
        }
        //未到拍摄时间
        if(!empty($data['wdpstime']) ){
            $wdpstime = time_StrToArr($data['wdpstime']);
            $map['wdpstime']=['between time',$wdpstime];
        }
        //成功拍摄时间
        if(!empty($data['cgpstime'])){
            $cgpstime = time_StrToArr($data['cgpstime']);
            $map['cgpstime']=['between time',$cgpstime];
        }
        //金牌匹配
        if(!empty($data['jinpai'])){
            $map['jinpai']=['eq',$data['jinpai']];
        }
        //会所地址
        if(!empty($data['hsdzid'])){
            $map['hsdzid']=['eq',$data['hsdzid']];
        }
        //会所组长
        if(!empty($data['hszzid'])){
            $map['hszzid']=['eq',$data['hszzid']];
        }
        //会所专员
        if(!empty($data['hszyid'])){
            $map['hszyid']=['eq',$data['hszyid']];
        }
        //会所状态
        if(!empty($data['hdstate'])){
            $map['hdstate']=['eq',$data['hdstate']];
        }
        //课程
        if(!empty($data['kcid'])){
            $map['kcid']=['eq',$data['kcid']];
        }

        //邀约分配时间
        if(!empty($data['yyfptime'])){
            $yyfptime = time_StrToArr($data['yyfptime']);
            $map['yyfptime']=['between time',$yyfptime];
        }
        //会所分配时间
        if(!empty($data['hsfptime'])){
            $hsfptime = time_StrToArr($data['hsfptime']);
            $map['hsfptime']=['between time',$hsfptime];
        }
        //会所领单时间
        if(!empty($data['hsldtime'])){
            $hsldtime = time_StrToArr($data['hsldtime']);
            $map['hsldtime']=['between time',$hsldtime];
        }
        //预约上课时间
        if(!empty($data['yysktime'])){
            $yysktime = time_StrToArr($data['yysktime']);
            $map['yysktime']=['between time',$yysktime];
        }
        //取消预约上课时间
        if(!empty($data['qxyytime'])){
            $qxyytime = time_StrToArr($data['qxyytime']);
            $map['qxyytime']=['between time',$qxyytime];
        }
        //报名时间
        if(!empty($data['hsbmtime'])){
            $hsbmtime = time_StrToArr($data['hsbmtime']);
            $map['hsbmtime']=['between time',$hsbmtime];
        }
        //上课时间
        if(!empty($data['skcgtime'])){
            $skcgtime = time_StrToArr($data['skcgtime']);
            $map['skcgtime']=['between time',$skcgtime];
        }
        //旷课时间
        if(!empty($data['hskktime'])){
            $hskktime = time_StrToArr($data['hskktime']);
            $map['hskktime']=['between time',$hskktime];
        }
        //反馈部门
//        if(!empty($data['fkbm'])){
//            $map['fkbm']=['eq',$data['fkbm']];
//        }
        //反馈人员
        if(!empty($data['fkry'])){
            $map['fkry']=['eq',$data['fkry']];
        }
        //反馈时间
        if(!empty($data['fktime'])){
            $fktime = time_StrToArr($data['fktime']);
            $map['fktime']=['between time',$fktime];
        }
        //订单类型
        if(!empty($data['daoru'])){
            $map['daoru']=['eq',$data['daoru']];
        }
        //订单类型
        if(!empty($data['yyreason'])){
            $map['yyreason']=['eq',$data['yyreason']];
        }

        /* 手机端 */
        //搜索ID或者手机号
        if(!empty($data['id_phonenum'])){
            $map['id|maphone|otherphone']=['eq',$data['id_phonenum']];
        }
        //今日追踪、
        $start = strtotime(date('Y-m-d 00:00:00'));
        $end = time();
        if($data['today_xinxi']=='today_zhuizong' && empty($data['zztime'])){
            $map['zztime']=['between time',[$start, $end]];
        }
        //今日邀约拍摄
        if($data['today_xinxi']=='today_yaoyuepaishe' && empty($data['yypstime'])){
            $map['yypstime']=['between time',[$start, $end]];
        }
        //今日报名课程
        if($data['today_xinxi']=='today_baomingkecheng' && empty($data['yysktime'])){//yysktime
            $map['yysktime']=['between time',[$start, $end]];
        }
        //今日取消拍摄
        if($data['today_xinxi']=='today_quxiaopaishe' && empty($data['qxpstime'])){
            $map['qxpstime']=['between time',[$start, $end]];
        }
        //今日拍摄成功
        if($data['today_xinxi']=='today_paishechenggong' && empty($data['cgpstime'])){
            $map['cgpstime']=['between time',[$start, $end]];
        }
        //今日分配订单
        if($data['today_xinxi']=='today_fenpeidingdan' && empty($data['yyfptime'])){
            $map['yyfptime']=['between time',[$start, $end]];
        }
        //今日拍摄
        if($data['today_xinxi']=='today_paishe' && empty($data['yypstime'])){
            $map['cgpstime']=['between time',[$start, $end]];
        }
        //今日分配（会所看）
        if($data['today_xinxi']=='today_fenpei' && empty($data['hsldtime'])){
            $map['hsfptime']=['between time',[$start, $end]];
        }
        //今日报名（会所看）
        if($data['today_xinxi']=='today_baoming' && empty($data['yysktime'])){
            $map['yysktime']=['between time',[$start, $end]];
        }
        //今日取消报名（会所看）
        if($data['today_xinxi']=='today_quxiaobaoming' && empty($data['qxyytime'])){
            $map['qxyytime']=['between time',[$start, $end]];
        }
        //今日未到（会所看）
        if($data['today_xinxi']=='today_weidao' && empty($data['hskktime'])){
            $map['hskktime']=['between time',[$start, $end]];
        }
        //今日邀约拍摄成功时间
        if($data['today_xinxi']=='today_yaoyuechenggong' && empty($data['yycgtime'])){
            $map['yycgtime']=['between time',[$start, $end]];
        }
        //预约今日拍摄
        if($data['today_xinxi']=='today_yuyuepaishe' && empty($data['yypstime'])){
            $map['yypstime']=['between time',[$start, $end]];
        }
        //今日反馈
        if($data['today_xinxi'] == 'today_fankui' && empty($data['fktime'])){
            $map['fktime']=['between time',[$start, $end]];
        }

        return $map;
    }

    /**
     * 组合条件筛选和角色筛选
     * @param array $map
     * @return array|mixed
     */
    public function maps($map){
        //$order = new Order();
        $data = $this->map($map);
        $mapjuese = $this->mapJueSe();
        if(empty($data)){
            $datas = $mapjuese;
        }elseif(empty($mapjuese)){
            $datas = $data;
        }else{
            $datas = array_merge($mapjuese,$data);
        }
        return $datas;
    }

    /**角色筛选条件
     * @return mixed
     */
    public function mapJueSe(){
        $map['status'] = 1;//开启的订单
        $user = session('admin_user');
        $jdry = Db::name('users')->where(['depar_id'=>$user['depar_id']])->cache('600')->column('id');
        $jdry[] = 0;
        //渠道经理、渠道主管、网络经理、网络主管
        if($this->hasRole('qudaojingli') || $this->hasRole('qudaozhuguan') || $this->hasRole('wangluojingli') || $this->hasRole('wangluozhuguan') ){
          //  $map['qd_depar'] = ['eq',$user['depar_id']];
            $map['daoru'] = ['in',[1,2]];
            if( !($this->hasRole('qudaojingli')) ) {
                $map['jdry|fkry'] = ['in', $jdry];
            }
        }
        //渠道专员、网络专员
        elseif( $this->hasRole('qudaozhuanyuan') || $this->hasRole('wangluozhuanyuan') ){
//            $map['jdry|fkry'] = ['eq',$user['adminid']];
            $map['daoru'] = ['in',[1,2]];
            $map['where']['jdry'] =$user['adminid'];
            $yiyuan = $this->getUserToYiyuan();
            if($yiyuan){
                $map['where']['yiyuan'] =explode(',',$yiyuan);
            }else{
                $map['where']['yiyuan'] = -1;//解决医院为空的订单
            }
            $map['where']['yctime'] = strtotime( Carbon::parse('+7 months')->endOfMonth() );
        }
        //邀约主管
        elseif ($this->hasRole('yaoyuezhuguan')){
//            $map['ygroup_id'] = $user['ygroup_id'];
            $map['yykf'] = $user['adminid'];
        }
        //邀约专员
        elseif($this->hasRole('yaoyuezhuanyuan')){
            $map['yykf'] = $user['adminid'];
        }
        //摄影经理
        elseif ($this->hasRole('sheyingjingli')){
            $map['yycg'] = ['not in',[0,'']];
        }
        //摄影调度
        elseif ($this->hasRole('sheyingdiaodu')){
            $map['yycg'] = $user['group_id'];
        }
        //会所经理
        elseif($this->hasRole('huodongjingli') ){
            $map['hsdzid'] = ['<>',0];
        }
        //会所主管
        elseif($this->hasRole('huodongzhuguan')  ){
            $map['hsdzid'] = $user['group_id'];
        }
        //会所专员
        elseif($this->hasRole('huodongzhuanyuan')){
            $map['hsdzid'] = $user['group_id'];
            $map['hszyid'] = $user['adminid'];
        }
        return $map;
    }

    public function maptixing($txact){
        if($txact == 1){
            $map['zztime'] = ['lt',strtotime(date('Y-m-d'))];
            $map['ywstate'] = ['not in',[3,5,6]];
            $map['status'] = 1;
        }
        return $map;
    }


    /*  新增或修改订单  */
    public function edit($data,$khd=1){
        $order_log = new Order_log;
        //新建
        if(empty($data['id'])){
            $data = $this->addData($data);

            $res = $this->validate(true)->save($data);
            //成功，更新日志
            if($res){
                //给邀约客服发微信
                $data['id'] = $this->id;
                $this->weixinToYykf($data);
                $data['operation'] = 1; //添加订单
                $ret = $order_log->log($data,$khd);//日志
                $this->autoWeixin($data,$data['ywstate']);
                //渠道新建单自动发短信（必须是渠道才能发短信）
                if(session('admin_user.depar_id') == 1){
                    $this->qdjd_Auto_Msg($data);
                }

                $this->autoMessage($data);
//                if( $msgkg == 1){   $this->autoMessage($data);  }//短信
                return ['status'=>'1','info'=>"新增成功",'url'=>url('olist')];
            }else{//失败
//                halt($this->getError());
                return json(['status'=>'0','info'=>$this->getError()]);
            }
        }else{//更新
            $wxkg  = $data['wxkg'];unset($data['wxkg']);
            $msgkg = $data['msgkg'];unset($data['msgkg']);
            $olddata = $this->where('id', $data['id'])->find();
            $data = $this->editData($data,$olddata);
//            if( ($olddata['ywstate'] != 1 && $olddata['ywstate'] != 4)  && $data['ywstate'] == 7 && $this->hasRole(['qudaojingli','qudaozhuguan','qudaozhuanyuan','wangluojingli','wangluozhuguan','wangluozhuanyuan','huodongjingli','huodongzhuguan','huodongzhuanyuan'])){
            if( ($olddata['ywstate'] != 1 && $olddata['ywstate'] != 4)  && $data['ywstate'] == 7 && in_array(session('admin_user.depar_id'),[1,2,4]) ){//渠道、网路、会所
                $ywstate = $data['ywstate'];
                unset($data['ywstate']);
            }
            $res = $this->allowField(true)->isUpdate(true)->save($data);
            //成功，更新日志
            if($res){
                $data['operation'] = 2; //编辑订单
                $ret = $order_log->log($data,$khd);//日志
//                if( ($olddata['ywstate'] != 1 && $olddata['ywstate'] != 4 ) && $ywstate == 7 && $this->hasRole(['qudaojingli','qudaozhuguan','qudaozhuanyuan','wangluojingli','wangluozhuguan','wangluozhuanyuan','huodongjingli','huodongzhuguan','huodongzhuanyuan'])){
                if( ($olddata['ywstate'] != 1 && $olddata['ywstate'] != 4 ) && $ywstate == 7 && in_array(session('admin_user.depar_id'),[1,2,4]) ){//渠道、网路、会所
                    $data['ywstate'] =  $olddata['ywstate'];
                }else{
                    $ywstate = $data['ywstate'];
                    //给转介绍人员发微信
                    $this->weixinToZjsry($data,$olddata);
                }
                //给邀约客服发微信
                $this->weixinToYykf($data,$olddata);
                if($wxkg  == 1 ){
                    $this->autoWeixin($data,$ywstate);
                }//微信开关
                if( $msgkg == 1){//发送短信的角色
                    $this->autoMessage($data);
                }
                //分页
                $session_p = session('map');
                if(empty($session_p['p'])){
                    return ['status'=>'1','info'=>'数据更新成功！','url'=>url("olist",['editid'=>$data['id']])];
                }else{
                    return ['status'=>'1','info'=>'数据更新成功！','url'=>url("olist",['editid'=>$data['id'],'p'=>$session_p['p']])];
                }
            }else{//失败
                return ['status'=>'0','info'=>'您没有更改任何数据，请修改后提交','url'=>url('edit',['id'=>$data['id']])];
            }
        }
    }

    /**新建订单的补充数据
     * @param $data
     * @return mixed
     */
    public function addData($data){
        $data['sjtime'] = time();//收集日期
        $data['jdtime'] = time();//建单时间
        $data['status'] = 1;  //订单启用
        $user = session('admin_user');
        $data['jdry']   = $user['adminid'];
        $data['daoru'] = 1;//建单
        if(empty($data['qd_depar'])){
            $data['qd_depar'] = $user['depar_id'];//建单部门
        }
        if(empty($data['ywstate'])){
            $data['ywstate'] = 1;//建单默认未跟进
        }
        if($data['ywstate'] == 7){//意向客资
            $data['fkbm'] = $user['depar_id'];//反馈部门
            $data['fkry'] = $user['adminid'];//反馈人员
            $data['fktime'] = time();
        }
        if($this->hasRole(['huodongzhuguan','huodongzhuanyuan']) && empty($data['hsdzid'])){
            $data['hsdzid'] = session('admin_user.group_id');
        }
        if(!empty($data['yykf'])){
            $userinfo = Db::name('users')->where(['id'=>$data['yykf'],'status'=>1])->field('id,ygroup_id')->find();
            $data['ygroup_id'] = $userinfo['ygroup_id'];
        }
        if($this->hasRole(['yaoyuezhuguan','yaoyuezhuanyuan']) && empty($data['yykf'])){
            $data['yykf'] = $user['adminid'];
            $data['ygroup_id'] = $user['ygroup_id'];
        }
        if($data['ywstate'] == 5){
            $data['yypsnum'] = 1;
            $data['yycgtime'] = time();
            if(!empty($data['yypstime']) || $data['yypstime'] != 0){
                if( strtotime($data['yypstime']) >= strtotime(Carbon::parse('+1 months')->toDateTimeString())){
                    $data['yyoneyuetsmsgtime'] = strtotime(Carbon::parse('+1 months')->toDateTimeString());
                    $data['yyoneyuetsmsgflag'] = 1;
                }
            }
        }
        if($data['ywstate'] == 6){
            $data['cgpstime'] == time();
        }
        if($data['hdstate'] == 76){
            $data['yyhdnum'] = 1;
        }
        return $data;
    }

    public function editData($data,$olddata){
//        if($data['ywstate'] == 7 && ($olddata['fkry'] == 0 || $olddata['fkry'] == '') && $this->hasRole(['qudaojingli','qudaozhuguan','qudaozhuanyuan','wangluojingli','wangluozhuguan','wangluozhuanyuan','huodongjingli','huodongzhuguan','huodongzhuanyuan']) ){//意向客资
        if($data['ywstate'] == 7 && $this->hasRole(['qudaojingli','qudaozhuguan','qudaozhuanyuan','wangluojingli','wangluozhuguan','wangluozhuanyuan','huodongjingli','huodongzhuguan','huodongzhuanyuan']) ){//意向客资
                $data['fkbm'] = session('admin_user.depar_id');//反馈部门
                $data['fkry'] = session('admin_user.adminid');//反馈人员
                $data['fktime'] = time();
        }
        if(!empty($data['yykf']) && $olddata['yykf'] != $data['yykf'] ){
            $userinfo = Db::name('users')->where(['id'=>$data['yykf'],'status'=>1])->field('id,ygroup_id')->find();
            $data['ygroup_id'] = $userinfo['ygroup_id'];
        }
        if($data['ywstate'] == 5 && $olddata['ywstate'] != 5){//预约成功
            $data['psautomsgflag'] = 2;//预约拍摄系统自动发短信标志
        }
        if($data['hdstate'] == 76 && $olddata['hdstate'] != 76){
            $data['hsautomsgflag'] = 2;//预约上课系统自动发短信标志
        }
        $data = $this->doIncNum($data,$olddata);//处理自增和时间
        return $data;
    }

    public function autoWeixin($data,$ywstate = ''){
        if( $data['ywstate'] == 7  && $this->hasRole(['qudaojingli','qudaozhuguan','qudaozhuanyuan','wangluojingli','wangluozhuguan','wangluozhuanyuan','huodongjingli','huodongzhuguan','huodongzhuanyuan']) ){
            $this->weixin($data,$ywstate);
        }
        if( $data['ywstate'] == 5 &&  $this->hasRole(['yaoyuejingli','yaoyuezhuguan','yaoyuezhuanyuan']) ){
            $this->weixin($data,$ywstate);
        }
    }
    public function autoMessage($data){
        //只有会所可以发送短信
        if( isset($data['hdstate']) && $data['hdstate'] == 76  && $this->hasRole(['huodongjingli','huodongzhuguan','huodongzhuanyuan']) ){
            $this->message($data);
        }
        //只有邀约可以发送短信
//        if( isset($data['ywstate']) && $data['ywstate'] == 5 &&  $this->hasRole(['yaoyuejingli','yaoyuezhuguan','yaoyuezhuanyuan']) ){
        if( isset($data['ywstate']) && $data['ywstate'] == 5 ){
            $this->message($data);
        }
    }

    public function qdjd_Auto_Msg($data){
        $msgdata['orderid'] = $data['id'];
        $msgdata['phone'] = $data['maphone'];
        $msgdata['sendid'] = session('admin_user.adminid');
        $msgdata['tempcode'] = 'SMS_106495009';
        $this->sendSmss($msgdata);
    }

    /**
     *处理次数增加 和 时间
     */
    public function doIncNum($data,$olddata){
        if($olddata){
            //业务状态
            if(!empty($data['ywstate'])){
                //预约拍摄时间有改动，重新判断是否发送1月后的提示短信
                if( strtotime($data['yypstime']) != 0 && strtotime($data['yypstime']) != $olddata['yypstime']  ){
//            if((strtotime($data['yypstime']) - time())/86400 >= 30){
                    if( strtotime($data['yypstime']) >= strtotime(Carbon::parse('+1 months')->toDateTimeString()) ){
                        $data['yyoneyuetsmsgtime'] = strtotime(Carbon::parse('+1 months')->toDateTimeString());
                        $data['yyoneyuetsmsgflag'] = 1;
                    }else{
                        $data['yyoneyuetsmsgtime'] = 0;
                        $data['yyoneyuetsmsgflag'] = 0;
                    }
                }

                if($data['ywstate'] == 5 && $olddata['ywstate'] <> 5 && !empty($data['yypstime'])){
                    $this->where('id', $data['id'])->setInc('yypsnum');//预约拍摄
                    if( $olddata['yycgtime'] == '1970-01-01' ){//预约成功时间新增一次，不更改
                        $data['yycgtime'] = time();//预约成功时间
                    }
                }elseif ($data['ywstate'] == 2 && $olddata['ywstate'] <> 2 ){
                    $this->where('id', $data['id'])->setInc('qxpsnum');//取消拍摄
                    $data['qxpstime'] = time();
                }elseif ($data['ywstate'] == 9 && $olddata['ywstate'] <> 9 ){
                    $this->where('id', $data['id'])->setInc('wdpsnum');//未到拍摄
                    $data['wdpstime'] = time();
                }
                if($data['ywstate'] == 6 && $olddata['ywstate'] <> 6 ){//成功拍摄
                    $data['cgpstime'] = time();
                }
            }
            //会所状态
            if(!empty($data['hdstate'])){
                if($data['hdstate'] == 76 && $olddata['hdstate'] <> 76 && !empty($data['yysktime'])){
                    $this->where('id', $data['id'])->setInc('yyhdnum');//预约上课次数，报名
                }
                if($data['hdstate'] == 79 && $olddata['hdstate'] <> 79 ){
                    $this->where('id', $data['id'])->setInc('qxhdnum');//取消预约上课
                    $data['qxyytime'] = time();
                }
                if($data['hdstate'] == 78 && $olddata['hdstate'] <> 78 ){
                    $this->where('id', $data['id'])->setInc('skcgnum');//上课成功
                    $data['skcgtime'] = time();
                }
                if($data['hdstate'] == 77 && $olddata['hdstate'] <> 77 ){
                    $this->where('id', $data['id'])->setInc('wdhdnum');//未到上课
                    $data['hskktime'] = time();//旷课
                }
            }
            //处理会所领单时间
            if($data['hszyid']!=0 && empty($olddata['hsldtime'])){
                $data['hsldtime'] = time();
            }
        }
        return $data;
    }


    /**
     *   编辑权限
     */
    public function getQuanxian(){
        $id     = input('id');
        $data   = $this->where('id',$id)->find();
        if(empty($data)){
            return ['msg'=>"未找到此订单！",'status'=>"2",'icon'=>2];
        }
        $nowuser = session('admin_user');
       if($this->hasRole('yaoyuejingli')){
            $action  = $this->getEditInfo($data['ywstate'],$id);
        }elseif ($this->hasRole(['qudaojingli','qudaozhuguan','wangluojingli','wangluozhuguan'])){
            $where = $nowuser['depar_id'] == $data['qd_depar'];
            $action  = $this->getEditInfo($data['ywstate'],$id,$where);
        }elseif( $this->hasRole('qudaozhuanyuan') || $this->hasRole('wangluozhuanyuan') ){
            $where = $nowuser['adminid'] == $data['jdry'];
            $action  = $this->getEditInfo($data['ywstate'],$id,$where);
        }elseif ($this->hasRole('yaoyuezhuguan')){
//            $where = $nowuser['ygroup_id'] == $data['ygroup_id'];
            $where = $nowuser['adminid'] == $data['yykf'];
            $action  = $this->getEditInfo($data['ywstate'],$id,$where);
        }elseif ($this->hasRole('yaoyuezhuanyuan')){
            $where = $nowuser['adminid'] == $data['yykf'];
            $action  = $this->getEditInfo($data['ywstate'],$id,$where);
        }elseif ($this->hasRole('huodongjingli')){
            $where =  (!empty($data['hsdzid']) || $data['hsdzid'] !=0) ;
            $action  = $this->getEditInfo($data['ywstate'],$id,$where);
        }elseif ($this->hasRole('huodongzhuguan')){
            $where = $nowuser['group_id'] == $data['hsdzid'];
            $action  = $this->getEditInfo($data['ywstate'],$id,$where);
        }elseif ($this->hasRole('huodongzhuanyuan')){
            $where = $nowuser['adminid'] == $data['hszyid'];
            $action  = $this->getEditInfo($data['ywstate'],$id,$where);
        }elseif ($this->hasRole('sheyingjingli')){
            $where =  (!empty($data['yycg']) || $data['yycg'] !=0) ;
            $action  = $this->getEditInfo($data['ywstate'],$id,$where);
//           $action = ['msg'=>"对不起，您没有权限修改！",'status'=>"0",'icon'=>4];//摄影经理不能修改
        }elseif ($this->hasRole('sheyingdiaodu')){
            $where = $nowuser['group_id'] == $data['yycg'];
            $action  = $this->getEditInfo($data['ywstate'],$id,$where);
        }else{
            $action = ['msg'=>"恭喜您有权限访问！",'status'=>"1","url"=>url('edit',['id'=>$id])];
        }
        return $action;
    }
    public function getEditInfo($state,$id,$where=''){
        if( $where === '' || $where === true){
            $ywstates = $this->getCanEditStates(); //能够编辑的状态组
        }else{
            return ['msg'=>"对不起，您没有权限修改！",'status'=>"0",'icon'=>4];
        }
        if(empty($where)){
            if( in_array($state,$ywstates) ){
                return ['msg'=>"恭喜您有权限访问！",'status'=>"1","url"=>url('edit',['id'=>$id])];
            }else{
                return ['msg'=>"对不起，您没有权限修改！",'status'=>"0",'icon'=>4];
            }
        }else{
            if( in_array($state,$ywstates) && $where ){
                return ['msg'=>"恭喜您有权限访问！",'status'=>"1","url"=>url('edit',['id'=>$id])];
            }else{
                return ['msg'=>"对不起，您没有权限修改！",'status'=>"0",'icon'=>4];
            }
        }
    }

    /**
     *处理分配专员或活动的动作，存数据库
     */
    public function fenpeiZy($data,$khd=1){
        if(empty($data['ids'])){
            return ['msg'=>'请选择订单！','icon'=>2,'url'=>url('fenpei_dingdan',['fpdata'=>1])];
        }else{
            $data['yyfptime'] = time();
            $data['automsgflag'] = 2;
            if(empty($data['automsgtime'])){$data['automsgtime'] = time();}
            $userinfo = Db::name('users')->where(['id'=>$data['yykf'],'status'=>1])->field('id,ygroup_id')->find();
            $data['ygroup_id'] = $userinfo['ygroup_id'];
            $res = $this->allowField(['yykf','yyfptime','ygroup_id','automsgtime','automsgflag'])->save($data, ['id' => ['in',$data['ids']]]);
            if($res){
                $order_log = new Order_log();
                $data['operation'] = 4;
                $order_log->log($data,$khd);
//                    $this->fenpeiMessage($data['ids'],$data['yykf']);//分配专员时发送短信
                return ['msg'=>'分配专员成功！','icon'=>1,'url'=>url('fenpei_dingdan',['fpdata'=>1])];
            }else{
                return ['msg'=>'分配专员失败！','icon'=>2,'url'=>url('fenpei_dingdan',['fpdata'=>1])];
            }

        }
    }

    public function fenpeiHs($data,$khd=1){
        if(empty($data['ids'])){
            return ['msg'=>'请选择订单！','icon'=>2,'url'=>url('fenpei_huisuo',['fpdata'=>1])];
        }else{
            $data['hsfptime'] = time();
            $users = Db::name('users')->where(['group_id'=>$data['hsdzid'],'status'=>1])->select();
            //寻找会所主管id
            foreach ($users as $val){
                if( $this->hasRole("huodongzhuguan",$val['id'])){
                    $data['hszzid'] = $val['id'];break;
                }
            }
            $res = $this->allowField(['hsdzid','hsfptime','hszzid'])->save($data, ['id' => ['in',$data['ids']]]);
            if($res){
                $order_log = new Order_log();
                $data['operation'] = 5;
                $order_log->log($data,$khd);
                return ['msg'=>'分配会所成功！','icon'=>1,'url'=>url('fenpei_huisuo',['fpdata'=>1])];
            }else{
                return ['msg'=>'分配会所失败！','icon'=>2,'url'=>url('fenpei_huisuo',['fpdata'=>1])];
            }
        }
    }

    public function weixinToYykf($data,$olddata=''){
        if(empty($olddata)){//新建单
            if( (!empty($data['yykf']) || $data['yykf'] != 0) && $data['yykf']!=$data['jdry']  ){
                $this->wxToYykf($data);
            }
        }else{//编辑订单
            if( (!empty($data['yykf']) || $data['yykf'] != 0) && ($data['yykf'] != $olddata['yykf']) ){
                $this->wxToYykf($data);
            }
        }
    }

    public function wxToYykf($data){
        $info = $this->where(['id'=>$data['id'],'status'=>1])->find();
        $wxdata = $this->weixinCommonData($data,$info);
        $wxdata['userid']=$data['yykf'];
        $wxdata['first']="经理下发了一条顾客订单！";
        $wxdata['keyword5']=$info['qdbz'];
        $this->sendWechat($wxdata);
    }

    public function weixinToZjsry($data,$olddata){
        //转介绍订单，并且业务状态发生变化,自动发微信给转介绍人
        if( !empty($data['ywstate']) && $data['ywstate'] != $olddata['ywstate'] && $olddata['daoru'] == 3 && $olddata['status'] == 1){
            $ordersinfo = Db::name('orders')->where(['order_id'=>$data['id']])->field('id')->find();
            $res = Db::name('orders')->update(['id'=>$ordersinfo['id'],'ywstate'=>$data['ywstate']]);//修改中间表
            if($res){
                dellZjsLog(['order_id'=>$ordersinfo['id'],'info'=>'自动修改状态','operation'=>4,'czry'=>session('admin_user.adminid')]);//中间表日志
                $sendhuashu = new SendHuaShua();
                $sendhuashu->sendMsg(['id'=>$ordersinfo['id'],'hslx'=>1]);
            }
        }
    }

    //分配专员时发送短信
    public function fenpeiMessage($ids,$yykf){
        if(!empty($ids)){
            foreach ($ids as $id){
                $info = $this->where(['id'=>$id])->field('maphone')->find();
                $msgdata['phone'] = $info['maphone'];
                $msgdata['sendid'] = session('admin_user.adminid');
                $msgdata['orderid'] = $id;
                $userinfo = DB::name('users')->where(['depar_id' => 3, 'id' => $yykf, 'status' => 1])->field('phone')->find();
                $msgdata['param'] = [ 'phone' => $userinfo['phone'] ];//邀约员工电话
                $msgdata['tempcode'] = 'SMS_68410086';
                $this->sendSmss($msgdata);
            }
        }
    }

    /* 处理微信推送 */
    /**
     * @param $data  array 订单数据
     */
    public function weixin($data,$ywstate){
        if($ywstate == 7 || $ywstate == 5){
            $info = $this->where(['id'=>$data['id'],'status'=>1])->find();
            $wxdata = $this->weixinCommonData($data,$info);
            if( $this->hasRole(["qudaojingli","qudaozhuguan","qudaozhuanyuan","wangluojingli","wangluozhuguan","wangluozhuanyuan"]) ){
                $wxdata['keyword5']=$data['qdbz'];
            }elseif( $this->hasRole(["yaoyuejingli","yaoyuezhuguan","yaoyuezhuanyuan"]) ){
                $wxdata['keyword5']=$data['yybz'];
            }elseif (  $this->hasRole(["huodongjingli","huodongzhuguan","huodongzhuanyuan"]) ){
                $wxdata['keyword5']=$data['hsbz'];
            }else{
                $wxdata['keyword5']=$data['qdbz'];
            }

            if($ywstate == 7 ){
//                $users = $this->getYykfID_Phone($info['yykf'])['id'];
                $users = getYykfID($info['yykf']);
                $wxdata['first']="推送了一条意向顾客信息！";
            }
            if($ywstate == 5){
                $yycg = $data['yycg'];
                if(!empty($yycg) && $yycg <> 0){
                    $user = Db::name('users')->where(['group_id'=>5,'status'=>1,'group_id'=>$data['yycg'],'weixinstatus'=>1])->field('id')->find();
                    if(empty($user)) {
                        return ['msg'=>"未找到此场馆调度或调度未绑定微信",'status'=>0,'icon'=>7,'url'=>url('pushweixin',['id'=>$data['id']])];
                    }
                    $users = $user['id'];
                }
                $wxdata['first']="推送了一条顾客拍摄信息！";
            }

            if(is_array($users)){//多个邀约经理，都要发送
                foreach ($users as $user){
                    $wxdata['userid']=$user;
                    $res = $this->sendWechat($wxdata);
//                    dump($wxdata);die;
                }
            }else{
                $wxdata['userid']=$users;
                $res = $this->sendWechat($wxdata);
            }
            if($res['errmsg'] == 'ok'){
                return ['msg'=>"微信推送成功",'status'=>1,'icon'=>1,'url'=>url('olist')];
            }else{
                return ['msg'=>"微信推送失败",'status'=>0,'icon'=>2,'url'=>url('pushweixin',['id'=>$data['id']])];
            }
        }
//        else{
//            return ['msg'=>"此状态不支持微信推送",'status'=>0,'icon'=>2,'url'=>url('pushweixin',['id'=>$data['id']])];
//        }
    }

    public function weixinCommonData($data,$info=''){
        if(empty($info)){
            $info = $this->where(['id'=>$data['id'],'status'=>1])->find();
        }
        $wxdata['orderid']=$data['id'];
        $wxdata['sendid']=session('admin_user.adminid');
        $wxdata['url']=url('mobile/index/edit',['id'=>$data['id']],true,true);
        $stateinfo = DB::name('state')->where(['id'=>$data['ywstate'],'status'=>1])->field('name')->find();
        $wxdata['keyword1'] = $info['name'];
        if(empty($info['otherphone']) || $info['otherphone'] == 0 ) {
            $wxdata['keyword2']=$info['maphone'];
        }else{
            $wxdata['keyword2']=$info['maphone']."/".$info['otherphone'];
        }
        $wxdata['keyword3']="{$stateinfo['name']}！";
        $wxdata['keyword4']=( $info['yypstime'] != "1970-01-01 8:00" )?$info['yypstime']:'';
        return $wxdata;
    }


    public function message($data){
        if( !empty($data['ywstate']) && $data['ywstate'] == 5 && !empty($data['yycg']) && !empty($data['yypstime']) ) {
            $orderinfo = $this->where(['id' => $data['id'], 'status' => 1])->find();
            $msgdata = $this->psMsgData($orderinfo);
            $msgdata['sendid'] = session('admin_user.adminid');
        }
        //预约课程
        if( !empty($data['hdstate']) && $data['hdstate'] == 76 && !empty($data['yysktime']) && !empty($data['kcid'])  ){
            $orderinfo = $this->where(['id' => $data['id'], 'status' => 1])->field('id,maphone,kcid,hsdzid,yyhdnum,yysktime')->find();
            $msgdata = $this->hsMsgData($orderinfo);
            $msgdata['sendid'] = session('admin_user.adminid');
        }
        return $this->sendSmss($msgdata);
    }

    public function psMsgData($data){
        $msgdata['phone'] = $data['maphone'];
        $msgdata['orderid'] = $data['id'];

        $yycginfo = Db::name('group')->where(['id' => $data['yycg'], 'status' => 1])->find();

        if($data['qd_depar'] == 2){
            $yaoyueInfo = Db::name('users')->where(['id'=>$data['jdry']])->find();//网络部找建单人员
        }else{
            $yaoyueInfo = getYykfInfo($data['yykf']);
        }
        $msgdata['param'] = [
            'time' => changeTime($data['yypstime']),
            'addr' => $yycginfo['address'],
            'phone' => $yycginfo['tel'],//摄影场电话
            'yykf' =>$yaoyueInfo['username'],
            'tel' => $yaoyueInfo['phone'],//邀约电话
        ];
        $msgdata['tempcode'] = 'SMS_105170038';
        return $msgdata;
    }

    public function hsMsgData($data){
        $msgdata['phone'] = $data['maphone'];
        $msgdata['orderid'] = $data['id'];

        $kcinfo = Db::name('leibie')->where(['id'=>$data['kcid'],'status'=>1])->field('name,address')->find();
        $hsinfo = Db::name('group')->where(['id'=>$data['hsdzid'],'status'=>1])->field('address,tel')->find();
        $msgdata['param'] = [   'addr'=>$hsinfo['address'], 'tel'=>$hsinfo['tel']   ];
        if($data['yyhdnum'] == 1){//第一次
            $msgdata['param']['kctimekcname'] = changeTime($data['yysktime'])."《".$kcinfo['name']."》".$kcinfo['address']."。";
            $msgdata['tempcode'] = 'SMS_67590232';
        }else{
            $msgdata['param']['kcsjmcjj'] = changeTime($data['yysktime'])."《".$kcinfo['name']."》".$kcinfo['address']."。";
            $msgdata['tempcode'] = 'SMS_67720286';
        }
        return $msgdata;
    }

    /**  获取邀约客服或邀约经理的ID和电话
     * @param $yykf
     * @return array
     */
    public function getYykfID_Phone($yykf){
        if( empty($yykf) || $yykf == 0 ){
//            $users = Db::name('users')->where(['depar_id'=>3,'status'=>1,'weixinstatus'=>1])->field('id')->select();
//            foreach ($users as $val){//寻找邀约经理id
//                if( $this->hasRole("yaoyuejingli",$val['id'])){
//                    $id[] = $val['id'];
////                    $userinfo = DB::name('users')->where(['depar_id'=>3,'id' => $val['id'],'status'=>1])->find();
////                    $yaoyuephone[] = $userinfo['phone'];
//                }
//            }
//            $yaoyuephone = implode(',',$yaoyuephone);
            $yykf = Db::name('users')->where(['depar_id'=>3,'status'=>1,'weixinstatus'=>1,'position'=>2])->cache(6000)->column('id');//寻找邀约经理

            //目前固定邀约经理为李雨珊
            $yaoyuejingli = Db::name('users')->where(['depar_id'=>3,'status'=>1,'id'=>13])->field('id,phone')->cache(6000)->find();
            $yaoyuephone = $yaoyuejingli['phone'];
        }else{
            $userinfo = DB::name('users')->where(['depar_id'=>3,'id' => $yykf,'status'=>1])->field('phone')->find();
            $yaoyuephone = $userinfo['phone'];
//            $id = $yykf;
        }
        return ['id'=>$yykf,'yaoyuephone'=>$yaoyuephone];
//        return ['id'=>$id,'yaoyuephone'=>$yaoyuephone];
    }


    /**
     * @param $map   array 提醒的筛选条件
     * @return Order|false|\PDOStatement|string|\think\Collection
     */
    public static function tixing($map){
        return Db::name('order')->where($map)->cache(600)->count();
    }

    /**
     * 转介绍订单
     * @return \think\model\relation\BelongsTo
     */
    public function user(){
        return $this->belongsTo('customer','tjr_id','id',[],"LEFT");
    }

    //经理简报
    public function jingli_Jianbao($time,$type){
        $map['cgps']    = [ 'status'=>1, 'ywstate'=>6, 'cgpstime'=>['between',$time] ];
        $map['yycg']   = [ 'status'=>1, 'ywstate'=>['in',[5,6,2,9]], 'yycgtime'=>['between',$time]];
        $map['yy']      = [ 'status'=>1, 'automsgtime'=>['between',$time] ];
        $map['yymonth'] = [ 'status'=>1, 'ywstate'=>['in',[5,6,2,9]],'yycgtime'=>['between',$time] ];
        $map['fkkz']    = [ 'status'=>1,'fkry'=>['neq',0],'fktime'=>['between',$time]];
        $map['zjs']     = [  'status'=>1,'daoru'=>3,'jdtime'=>['between',$time]  ];
        //来电预约成功
        $map['laidian'] = [  'status'=>1,'qd_depar'=>3,'jdtime'=>['between',$time], 'ywstate'=>['in',[5,6,2,9]] ,'yycgtime'=>['between',$time] ];
        $data = $this->jianbao_Data($map,$type);
        $data['qdjd'] = self::getQdjdData($time);
        return $data;
    }
    //主管简报
    public function zhuguan_Jianbao($time,$ygroup,$type){
        $map['cgps']    = [ 'status'=>1, 'ywstate'=>6, 'cgpstime'=>['between',$time],'ygroup_id'=>$ygroup ];
        $map['yycg']    = [ 'status'=>1, 'ywstate'=>['in',[5,6,2,9]], 'yycgtime'=>['between',$time] ,'ygroup_id'=>$ygroup ];
        $map['yy']      = [ 'status'=>1, 'automsgtime'=>['between',$time],'ygroup_id'=>$ygroup ];
        $map['yymonth'] = [ 'status'=>1, 'ywstate'=>['in',[5,6,2,9]],'yycgtime'=>['between',$time],'ygroup_id'=>$ygroup ];
        $map['fkkz']    = [ 'status'=>1,'fkry'=>['neq',0],'fktime'=>['between',$time],'ygroup_id'=>$ygroup ];
        $map['zjs']     = [  'status'=>1,'daoru'=>3,'jdtime'=>['between',$time] ,'ygroup_id'=>$ygroup ];
        //来电预约成功
        $map['laidian'] = [  'status'=>1,'qd_depar'=>3,'jdtime'=>['between',$time], 'ywstate'=>['in',[5,6,2,9]] ,'yycgtime'=>['between',$time] ];
        $data = $this->jianbao_Data($map,$type);
        $data['qdjd'] = self::getQdjdData($time);
        return $data;
    }
    //专员简报
    public function zhuanyuan_Jianbao($time,$uid,$type){
        $map['cgps']    = [ 'status'=>1, 'ywstate'=>6, 'cgpstime'=>['between',$time],'yykf'=>$uid  ];
        $map['yycg']    = [ 'status'=>1, 'ywstate'=>['in',[5,6,2,9]], 'yycgtime'=>['between',$time],'yykf'=>$uid ];
        $map['yy']      = [ 'status'=>1, 'automsgtime'=>['between',$time],'yykf'=>$uid  ];
        $map['yymonth'] = [ 'status'=>1, 'ywstate'=>['in',[5,6,2,9]],'yycgtime'=>['between',$time],'yykf'=>$uid ];
        $map['fkkz']    = [ 'status'=>1,'fkry'=>['neq',0],'fktime'=>['between',$time],'yykf'=>$uid ];
        $map['zjs']     = [  'status'=>1,'daoru'=>3,'jdtime'=>['between',$time] ,'yykf'=>$uid  ];
        //来电预约成功
        $map['laidian'] = [  'status'=>1,'qd_depar'=>3,'jdtime'=>['between',$time], 'ywstate'=>['in',[5,6,2,9]] ,'yycgtime'=>['between',$time] ];
        $data = $this->jianbao_Data($map,$type);
        $data['qdjd'] = self::getQdjdData($time);
        return $data;
    }

    //简报数据
    public  function jianbao_Data($map,$type){
        $data['cgps'] = self::getPscgData($map['cgps']);
        $data['yycg'] = self::getYycgData($map['yycg']);
        $data['yymx'] = self::getYyData($map['yy']);
        $data['nextmonth'] = self::getYyNextMonth($map['yymonth']);
        $data['fkkz'] = self::getFkkzData($map['fkkz']);
        $data['zjs'] = self::getZjsData($map['zjs']);
        $data['laidian'] = self::getLaidianData($map['laidian']);
        return $data;
    }

    public function getQdjdData($time){
        $data['all'] = Db::name('order')->where( ['status'=>1,'qd_depar'=>1, 'jdtime'=>['between',$time]] )->count();
        return $data;
    }
    //拍摄场馆
    public function getPscgData($mapcgps){
        $datas = collect(Db::name('order')->where( $mapcgps )->field('id,yycg')->select());

        $data['all'] = $datas->count();
        $changguan = Db::name('group')->where( ['status'=>1,'depar_id'=>5] )->field('id,title')->cache(6000)->select();
        foreach ($changguan as $val){
            $data['detail'][] = ['name'=>$val['title'],'num'=>$datas->where('yycg',$val['id'])->count()] ;//成功拍摄
        }
        unset($datas);
        return $data;
    }
    //预约场馆
    public function getYycgData($mapyycg){
        $datas = collect(Db::name('order')->where( $mapyycg )->field('id,yycg')->select());
        $data['all'] = $datas->count();
        $changguan = Db::name('group')->where( ['status'=>1,'depar_id'=>5] )->field('id,title')->cache(6000)->select();
        foreach ($changguan as $val){
            $data['detail'][]    = ['name'=>$val['title'],'num'=>$datas->where('yycg',$val['id'])->count()];
        }
        unset($datas);
        return $data;
    }
    //预约明细
    public function getYyData($mapyy){
        $datas = collect(Db::name('order')->where( $mapyy )->field('id,ywstate')->select());
        $data1['zkz'] = $datas->count();
        $data1['wxkz'] =$datas->where('ywstate',3)->count();

        $data1['yxkz'] = $data1['zkz'] - $data1['wxkz'];//有效客资
        $data1['yycgkz'] = $datas->whereIn('ywstate',[5,6,2,9])->count();
        $data['all'] = $data1['zkz'];
        $data['detail'] = [
            ['name'=>'总客资','num'=>$data1['zkz']],
            ['name'=>'无效客资','num'=>$data1['wxkz']],
            ['name'=>'有效客资','num'=>$data1['yxkz']],
            ['name'=>'预约成功客资','num'=>$data1['yycgkz']],
        ];
        unset($datas);
        return $data;
    }

    //当月及往后三个月
    public function getYyNextMonth($mapyymonth){
        if( date('d',time()) == 31 || date('m-d',time()) == '11-29' || date('m-d',time()) == '11-30' ){
            for($i =0 ;$i<=3 ;$i++){
                $yynum = Db::name('order')->where( $mapyymonth )->where( 'yypstime',['between', [
                    strtotime(Carbon::parse("+$i months -5days")->startOfMonth()->toDateTimeString()),
                    strtotime(Carbon::parse("+$i months -5days")->endOfMonth()->toDateTimeString()),]]  )->count();
                $month_name = date('m',strtotime("+{$i}month -5days"));
                $data['detail'][] = ['name'=>$month_name.'月','num'=>$yynum];
            }
        }else{
            for($i =0 ;$i<=3 ;$i++){
                $yynum = Db::name('order')->where( $mapyymonth )->where( 'yypstime',['between', [
                    strtotime(Carbon::parse("+$i months")->startOfMonth()->toDateTimeString()),
                    strtotime(Carbon::parse("+$i months")->endOfMonth()->toDateTimeString()),]]  )->count();
                $month_name = date('m',strtotime("+{$i}month"));
                $data['detail'][] = ['name'=>$month_name.'月','num'=>$yynum];
            }
        }
        return $data;
    }
    //今天约的往后的月份
    public function getYyNextDay($mapyymonth){
        if( date('d',time()) == 31 || date('m-d',time()) == '11-29' || date('m-d',time()) == '11-30' ){
            for($i =0 ;$i<=3 ;$i++){
                $yynum = Db::name('order')->where( $mapyymonth )->where( ['yypstime'=>['between',[
                    strtotime( Carbon::parse("+$i months -5days")->startOfMonth()->toDateTimeString() ),
                    strtotime( Carbon::parse("+$i months -5days")->endOfMonth()->toDateTimeString() ),]],'yycgtime'=>['between',Time::today()] ] )->count();
                $month_name = date('m',strtotime("+{$i}month -5days"));
                $data['detail'][] = ['name'=>$month_name.'月','num'=>$yynum];
            }
        }else{
            for($i =0 ;$i<=3 ;$i++){
                $yynum = Db::name('order')->where( $mapyymonth )->where( ['yypstime'=>['between',[
                    strtotime(Carbon::parse("+$i months")->startOfMonth()->toDateTimeString()),
                    strtotime(Carbon::parse("+$i months")->endOfMonth()->toDateTimeString()),]],'yycgtime'=>['between',Time::today()] ] )->count();
                $month_name = date('m',strtotime("+{$i}month"));
                $data['detail'][] = ['name'=>$month_name.'月','num'=>$yynum];
            }
        }
        return $data;
    }

    //反馈客资
    public function getFkkzData($mapfkkz){
        $datas = collect(Db::name('order')->where( $mapfkkz )->field('id,ywstate,fkbm')->select());
        $data['all_all'] = $datas->count();
        $data['all'] = $datas->whereIn('ywstate',[5,6,2,9])->count();
        $data['detail'] = [
            [
                'name'=>'渠道',
                'num'=> $datas->whereIn('ywstate',[5,6,2,9])->where('fkbm',1)->count(),
                'num_all'=>$datas->where('fkbm',1)->count()
            ],
            [
                'name'=>'网络',
                'num'=> $datas->whereIn('ywstate',[5,6,2,9])->where('fkbm',2)->count(),
                'num_all'=>$datas->where('fkbm',2)->count()
            ],
            [
                'name'=>'会所',
                'num'=> $datas->whereIn('ywstate',[5,6,2,9])->where('fkbm',4)->count(),
                'num_all'=>$datas->where('fkbm',4)->count()
            ],
        ];
        unset($datas);
        return $data;
    }
    //转介绍
    public function getZjsData($mapzjs){
        $datas = collect(Db::name('order')->where( $mapzjs )->field('id,ywstate')->select());
        $data['all'] = $datas->count();
        $data['cgyy'] = $datas->whereIn('ywstate',[5,6,2,9])->count();
        unset($datas);
        return $data;
    }
    //来电
    public function getLaidianData($maplaidian){
        $datas = collect(Db::name('order')->where( $maplaidian )->field('id,ywstate')->select());
        $data['cgyy'] = $datas->count();
        return $data;
    }


}

?>